//
//  KLSGEditorRecommendViewController.m
//  KaoLaShiGuangFM
//
//  Created by lanou3g on 15/10/29.
//  Copyright © 2015年 com.lanou3g. All rights reserved.
//

#import "KLSGEditorRecommendViewController.h"
#import "KLSGBrifAndVoiceViewController.h"
#import "KLSGDataFail.h"
#import "DDIndicator.h"

@interface KLSGEditorRecommendViewController ()<UITableViewDataSource, UITableViewDelegate>
{
    // 保存页码
    NSInteger pageId;
}

@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) KLSGRecommendTool *tool;

@property (nonatomic, strong) KLSGDataFail *failView;
@property (nonatomic, strong) NSMutableArray *dataArray;

// 加载指示器
@property (nonatomic, strong) DDIndicator *indicator;

@end

@implementation KLSGEditorRecommendViewController

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:YES];
    self.tabBarController.tabBar.hidden = YES;
    
    [self setupData];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self subView];
    pageId = 1;
    [self setupRefresh];
    self.title = @"推荐";
}

// 懒加载
- (KLSGDataFail *)failView
{
    if (!_failView) {
        _failView = [[KLSGDataFail alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight)];
    }
    return _failView;
}

- (KLSGRecommendTool *)tool
{
    if (!_tool) {
        _tool = [[KLSGRecommendTool alloc] init];
    }
    return _tool;
}

- (NSMutableArray *)dataArray
{
    if (!_dataArray) {
        _dataArray = [NSMutableArray array];
    }
    return _dataArray;
}

// 加载数据
- (void)setupData
{
    [self.failView hidden];
    NSString *url = kEditorRecommendUrl((long)pageId);
    __block KLSGEditorRecommendViewController *mySelf = self;
    [self.tool setupEditorReDataWithUrl:url successBlock:^(NSData *data) {
        // 解析
        if (data != nil) {
            NSMutableDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:(NSJSONReadingMutableContainers) error:nil];
            // 取出需要的数据
            NSArray *resultArray = dic[@"list"];
            
            // 遍历数组给model赋值,并保存到数组中
            for (NSDictionary *dic in resultArray) {
                KLSGEditorReModel *model = [[KLSGEditorReModel alloc] init];
                [model setValuesForKeysWithDictionary:dic];
                [mySelf.dataArray addObject:model];
            }
            // 解析数据完成后
            [mySelf.tableView reloadData];
        }
    } failBlock:^{
        [mySelf.failView netRequestFailWithBlock:^{
            [mySelf setupData];
            
        }];
        [mySelf.tableView addSubview:mySelf.failView];
    }];
}

// 下拉刷新，上拉加载
- (void)setupRefresh
{
    [self.tableView addHeaderWithTarget:self action:@selector(headerRefreshing)];
    [self.tableView headerBeginRefreshing];
    self.tableView.headerPullToRefreshText = @"下拉可以刷新";
    self.tableView.headerRefreshingText = @"正在加载";
    self.tableView.headerReleaseToRefreshText = @"松开马上刷新";
    
    [self.tableView addFooterWithTarget:self action:@selector(footerRefreshing)];
    self.tableView.footerPullToRefreshText = @"下拉可以刷新";
    self.tableView.footerRefreshingText = @"正在加载";
    self.tableView.footerReleaseToRefreshText = @"松开马上刷新";
}
- (void)headerRefreshing
{
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        _dataArray = nil;
        pageId = 1;
        [self setupData];
        [self.tableView headerEndRefreshing];
    });
}
- (void)footerRefreshing
{
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
         pageId++;
        if (pageId <= 50) {
            [self setupData];
        }
        [self.tableView footerEndRefreshing];
    });
}

- (void)subView
{
    self.tableView = [[UITableView alloc] initWithFrame:self.view.frame style:(UITableViewStylePlain)];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.view addSubview:self.tableView];
    
    // 注册cell
    [self.tableView registerClass:[KLSGRecommendTableCell class] forCellReuseIdentifier:@"cell"];
    
    // 设置leftBarButton
    UIBarButtonItem *left = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:(UIBarButtonSystemItemReply) target:self action:@selector(leftReturn)];
    left.tintColor = [UIColor colorWithRed:234 / 256.0 green:79 / 256.0 blue:56 / 256.0 alpha:1];
    self.navigationItem.leftBarButtonItem = left;
}

// leftBarButton 响应事件
- (void)leftReturn
{
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark -实现tableView的代理方法
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.dataArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    KLSGRecommendTableCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath];
    // 保护，数组越界
    if (self.dataArray.count >= indexPath.row) {
        KLSGEditorReModel *model = self.dataArray[indexPath.row];
        cell.title.text = model.title;
        cell.detail.text = model.intro;
        cell.playCountLabel.text = [NSString stringWithFormat:@"%.1f万", [model.playsCounts floatValue] / 10000];
        [cell.collectButton addTarget:self action:@selector(collectionAction:) forControlEvents:(UIControlEventTouchUpInside)];
        cell.albumCountLabel.text = [NSString stringWithFormat:@"%@集", model.tracksCounts];
        [cell.picture sd_setImageWithURL:[NSURL URLWithString:model.coverMiddle]];
    }
   
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 85;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    KLSGBrifAndVoiceViewController *brifAndVoiceVC = [[KLSGBrifAndVoiceViewController alloc] init];
    if (self.dataArray.count < indexPath.row) {
        return;
    }
    KLSGEditorReModel *model = self.dataArray[indexPath.row];
    brifAndVoiceVC.albumIdString = [NSString stringWithFormat:@"%@", model.albumId];
    
    KLSGKindModel *kindModel = [[KLSGKindModel alloc] init];
    kindModel.albumCoverUrl290 = model.albumCoverUrl290;
    kindModel.title = model.title;
    kindModel.intro = model.intro;
    kindModel.playsCounts = model.playsCounts;
    kindModel.tracksCounts = model.tracks;
    kindModel.albumId = model.albumId;
    brifAndVoiceVC.model = kindModel;
    
    [self.navigationController pushViewController:brifAndVoiceVC animated:YES];
}

#pragma mark -收藏
- (void)collectionAction:(UIButton *)sender
{
    KLSGDB *dbManager = [[KLSGDB alloc] init];
    KLSGRecommendTableCell *cell =(KLSGRecommendTableCell *)[sender superview];
    NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
    KLSGEditorReModel *model = self.dataArray[indexPath.row];
    if ([dbManager queryKindWithAlbumId:model.albumId]) {
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"已经收藏" preferredStyle:(UIAlertControllerStyleAlert)];
        [self presentViewController:alert animated:YES completion:nil];
        [self performSelector:@selector(dismissAlert:) withObject:alert afterDelay:0.5
         ];
        
    } else {
        [dbManager createTable];
        [dbManager insertWithEditorReModel:model];
        
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"收藏成功" preferredStyle:(UIAlertControllerStyleAlert)];
        [self presentViewController:alert animated:YES completion:nil];
        [self performSelector:@selector(dismissAlert:) withObject:alert afterDelay:0.3
         ];
    }
}

- (void)dismissAlert:(UIAlertController *)alert
{
    [alert dismissViewControllerAnimated:YES completion:nil];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
    
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
